package com.cskaoyan.wx.controller;

import com.cskaoyan.bean.login_demo.BaseRespVo;
import com.cskaoyan.bean.reverseengineering.MarketKeyword;
import com.cskaoyan.bean.reverseengineering.MarketSearchHistory;
import com.cskaoyan.wx.bean.vo.searchvo.SearchIndexVO;
import com.cskaoyan.wx.service.SearchService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @description:
 * @author: lxc
 * @date: 2022/5/7 17:19
 */
@RequestMapping("wx/search")
@RestController
public class WxSearchController {

    @Autowired
    SearchService searchService;

    /**
     * 搜索模块，首页
     *
     * @return
     */
    @RequestMapping("index")
    public BaseRespVo SearchIndex() {

        // 显示默认搜索
        MarketKeyword marketDefaultKeyword = searchService.selectDefaultKeyWord();

        // 显示搜索历史
        // TODO: 根据用户名显示搜索历史
        Subject subject = SecurityUtils.getSubject();
        String username = null;
        if (subject.isAuthenticated()) {
            username = (String) subject.getPrincipals().getPrimaryPrincipal();
        }
        List<MarketSearchHistory> marketSearchHistorys = searchService.selectMarketSearchHistory(username);

        // 显示热门搜索
        List<MarketKeyword> marketHotKeywords = searchService.selectHotKeyWord();

        SearchIndexVO searchIndexVO = new SearchIndexVO(marketDefaultKeyword, marketHotKeywords, marketSearchHistorys);

        return BaseRespVo.ok(searchIndexVO, "成功", 0);
    }

    /**
     * 搜索模块，搜索提示
     *
     * @param keyword
     * @return
     */
    @RequestMapping("helper")
    public BaseRespVo searchHelper(String keyword) {

        String[] names = searchService.selectGoodByGoods(keyword);

        return BaseRespVo.ok(names, "成功", 0);
    }

    /**
     * 搜索模块，清空搜索历史
     *
     * @return
     */
    @RequestMapping("clearhistory")
    public BaseRespVo searchClearHistory() {

        int affectedRows = searchService.updateSearchHistory();

        if (affectedRows == 0) {
            return BaseRespVo.ok(null, "删除失败", 500);
        }

        return BaseRespVo.ok(null, "成功", 0);
    }
}
